using UnityEngine;
using System.Collections;

public class shooting : MonoBehaviour 
{
    public GameObject[] Guns;

    public static int gunPicked = 0;
    public static bool reloading = false, zoomed = false;
    public GameObject gunCam, GunsAnimator;


    private bool shotPlease = false, stopShot = false , fireButtonDown = false;
    private int switching = 0;
    private float amo = 0, backpack = 0, otherWeponeAmo = -1;
    private float showcursor = 0;


    private void Start()
    {
        //if (networkView.isMine)
        //    StartCoroutine(Shoot(0));
        //else
        //    this.enabled = false;

        switching = 1;
        switchWep();
    }

    private void switchWep()
    {
        GunsAnimator.animation.Stop();
        if (switching == 1)
        {
            for (int a = 0; a < Guns.Length; a++)
            {
                if (gunPicked != a && Guns[a].GetComponent<Gun>().currentAmmo != 0)
                {
                    float temp = amo;

                    Guns[gunPicked].GetComponent<Gun>().currentAmmo = amo + backpack;
                    gunPicked = a;
                    if (otherWeponeAmo == -1)
                    {
                        amo = Guns[a].GetComponent<Gun>().currentAmmo;
                        backpack = 0;
                        while (amo > Guns[a].GetComponent<Gun>().maxMagAmo)
                        {
                            amo--;
                            backpack++;
                        }
                    }
                    else
                    {
                        amo = otherWeponeAmo;
                        backpack = Guns[a].GetComponent<Gun>().currentAmmo - otherWeponeAmo;
                    }

                    otherWeponeAmo = temp;
                    break;
                }
                else
                    continue;
            }
            Invoke("ReturnArms", GunsAnimator.animation["Switch Weapone"].length);
        }
    }

    private void ReturnArms()
    {
        GunsAnimator.animation["Switch Weapone"].time = GunsAnimator.animation["Switch Weapone"].length;
        GunsAnimator.animation["Switch Weapone"].speed = -1;
        GunsAnimator.animation.Play();
        switching = 0;
    }

    private void Update()
    {

        if (showcursor > 0)
            showcursor -= Time.deltaTime;

        //only show the gun being used
        for (int g = 0; g < Guns.Length; g++)
        {
            if (gunPicked != g)
            {
                foreach (GameObject r in Guns[g].GetComponent<Gun>().rendererObjects)
                {
                    r.GetComponent<Renderer>().enabled = false;
                }
            }
            else
            {
                foreach (GameObject r in Guns[g].GetComponent<Gun>().rendererObjects)
                {
                    r.GetComponent<Renderer>().enabled = true;
                }
            }
        }

        //Reload Check
        if (switching == 0 && !reloading && (Input.GetKeyDown(KeyCode.R) || (amo <= 0 && backpack > 0)))
        {
            reloading = true;
            Guns[gunPicked].animation.Play(Guns[gunPicked].GetComponent<Gun>().reloadAnimation);
            while (amo != Guns[gunPicked].GetComponent<Gun>().maxMagAmo || backpack == 0)
            {
                amo++;
                backpack--;
            }
            Invoke("FinishReload", Guns[gunPicked].animation[Guns[gunPicked].GetComponent<Gun>().reloadAnimation].length);
        }

        //Switching wepones if not zoomed in
        if (!zoomed)
        {

            if ((Input.GetKeyDown(KeyCode.Alpha1) || Input.GetKeyDown(KeyCode.Alpha2) || Input.GetAxis("Mouse ScrollWheel") != 0 ) && switching == 0)
            {
                switching = 1;
                fireButtonDown = false;
                GunsAnimator.animation.Stop();
                GunsAnimator.animation["Switch Weapone"].time = 0;
                GunsAnimator.animation["Switch Weapone"].speed = 1;
                GunsAnimator.animation.Play("Switch Weapone");
                Invoke("switchWep", GunsAnimator.animation["Switch Weapone"].length);
            }
        }
        //Zoom Functionality
        if (Input.GetButtonDown("Fire2") && switching == 0)
        {
            if (zoomed)
            {
                zoomed = false;
                gunCam.animation[Guns[gunPicked].GetComponent<Gun>().aimAnimation].time = gunCam.animation[Guns[gunPicked].GetComponent<Gun>().aimAnimation].length;
                gunCam.animation[Guns[gunPicked].GetComponent<Gun>().aimAnimation].speed = -1;
                gunCam.animation.Play(Guns[gunPicked].GetComponent<Gun>().aimAnimation);
                
            }
            else
            {
                gunCam.animation[Guns[gunPicked].GetComponent<Gun>().aimAnimation].time = 0;
                gunCam.animation[Guns[gunPicked].GetComponent<Gun>().aimAnimation].speed = 1;
                gunCam.animation.Play(Guns[gunPicked].GetComponent<Gun>().aimAnimation);
                Invoke("zoom", gunCam.animation[Guns[gunPicked].GetComponent<Gun>().aimAnimation].length);
                zoomed = true;
            }
        }
        //Mouse button 0 Detection
        if (Input.GetButtonDown("Fire1") && switching == 0)
        {
            stopShot = true;
            fireButtonDown =true;
        }

        if (Input.GetButtonUp("Fire1"))
        {
            fireButtonDown = false;
        }

        if (fireButtonDown)
        {
            shotPlease = true;
        }
    }

    private void zoom()
    {
        gunCam.transform.LookAt(Guns[gunPicked].GetComponent<Gun>().zoomLookAt.transform.position);
    }

    //Finish Reload
    private void FinishReload()
    {
        reloading = false;
    }

    IEnumerator Shoot(int semiCount)//Shooting Function In a loop
    {
        Gun g = Guns[gunPicked].GetComponent<Gun>();
        if (!reloading && stopShot && shotPlease && switching == 0 && amo > 0)
        {
            //play animations and add effects


            //Do raycasting
            Ray ray = Camera.main.ScreenPointToRay(new Vector3(Input.mousePosition.x, Input.mousePosition.y - 20, Input.mousePosition.z));
            RaycastHit hit;
            if (Physics.Raycast(ray, out hit, g.bulletDistance))
            {
                if (tag == "Player")
                {
                    if (hit.collider.gameObject.tag == "Player")
                    {
                        hit.collider.gameObject.networkView.RPC("LowerHealth", RPCMode.AllBuffered, hit.collider.gameObject.GetComponent<playerScript>().health - g.damage);
                    }
                }
            }
            if (g.currentTactic != Gun.tactical.suppressor)
                showcursor = 20;

            amo--;
        }

        if (shotPlease)
        {
            //Semi automatic repeate
            if (Guns[gunPicked].GetComponent<Gun>().type == Gun.ShootingType.Semi_Automatic && semiCount != 3)
            {
                yield return new WaitForEndOfFrame();
                StartCoroutine(Shoot(semiCount + 1));
            }
            //wait for fireDelay
            yield return new WaitForSeconds(Guns[gunPicked].GetComponent<Gun>().fireDelay);

            if (Guns[gunPicked].GetComponent<Gun>().type != Gun.ShootingType.Automatic)
                stopShot = false;

            shotPlease = false;
            StartCoroutine(Shoot(0));
        }
        else
        {
            yield return new WaitForEndOfFrame();
            StartCoroutine(Shoot(0));
        }
    }

    private void OnGUI()
    {
        GUILayout.Box(amo + "||" + backpack);
    }
}
